package com.mdx.rest.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mdx.rest.security.JWTProvider;
import org.apache.ibatis.annotations.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 当访问接口没有权限时，自定义返回结果
 * @author : jiagang
 * @date : Created in 2022/2/10 10:29
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private JWTProvider jwtProvider;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException  {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        Map<String, Object> results = new HashMap<>();
        results.put("code",403);
        results.put("msg","权限不足，请联系管理员!");
        out.write(new ObjectMapper().writeValueAsString(results));
        out.flush();
        out.close();

    }
}
